/**
 * Copyright 2010-2025 The mTASK Project Authors. All Rights Reserved.
 * Licensed under the MIT License (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.gitee.com/lort/mTask/LICENSE.md
 * Author: luyunyi @luyunyi2019@outlook.com
 */
#include <mTask.h>

void mListInsertFront(mList_t *root, mListNode_t *node)
{
    if(root->next==NULL)
    {
        root->next = node;
        root->pre = node;
        node->pre = root;
        node->next = NULL;
    }
    else
    {
        mListNode_t *head;
        head = root->next;
        node->next = head;
        head->pre = node;
        root->next = node;
        node->pre = root;
    }
}
void mListInsertTail(mList_t *root, mListNode_t *node)
{
    if(root->next==NULL)
    {
        root->next = node;
        root->pre = node;
        node->pre = root;
        node->next = NULL;
    }
    else
    {
        mList_t *rear;
        rear = root->pre;
        rear->next = node;
        node->next = NULL;
        node->pre = rear;
        root->pre = node;
    }
}
mListNode_t* mListDetachNode(mList_t *root, mListNode_t* node)
{
    mList_t *pcur;
    mTaskPrint(DBG_ERROR,"mListDetachNode at address:%lx !!!!\r\n",(uint64_t)node);
    for(pcur=root->next; pcur!=NULL; pcur=pcur->next)
    {
        if(pcur==node)
        {
            mTaskPrint(DBG_ERROR,"mListDetachNode at address:%lx == %lx \r\n",(uint64_t)pcur,(uint64_t)node);
            mListNode_t *pre = pcur->pre;
            mListNode_t *pnext = pcur->next;
            if(pre!=NULL)
                pre->next = pnext;
            if(pnext!=NULL)
                pnext->pre = pre;
            if(root->pre==node)
            {
                root->pre = (pre==root)?NULL:pre;
            }
            node->pre = NULL;
            node->next = NULL;
            return node;
        }
    }
    return NULL;
}
mListNode_t* mListDetachFront(mList_t *root)
{
    return mListDetachNode(root,root->next);
}
mListNode_t* mListDetachTail(mList_t *root)
{
    return mListDetachNode(root,root->pre);
}
void mListRemoveNode(mList_t *root, mListNode_t *node)
{
    mListNode_t *item = mListDetachNode(root,node);
    if(item!=NULL)
    {
        free(item);
    }
    else
    {
        mTaskPrint(DBG_ERROR,"Remove Node Error at address:%lx \r\n",(uint64_t)node);
    }
}
int mListCountNode(mList_t *root)
{
    mListNode_t *pcur;
    int count = 0;
    for(pcur=root->next; pcur!=NULL; pcur=pcur->next)
    {
        count++;
    }
    return count;
}
